package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.hardware.bcreader.BCRBarCodeValue;
import android.hardware.bcreader.BCRListener;
import android.hardware.bcreader.BCRManager;
import android.hardware.bcreader.BCRTicketInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.List;

import mytools.ApplicationUtil;
import mytools.DateUtil;
import mytools.MyBaseActivity;
import objects.InPatient;
import objects.OC_YZJH_Detail;
import objects.OrderDetail;
import service.WebService;

public class OrdersCheckActivity extends MyBaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    private String TAG = "BCRSample";
    private BCRManager mBCRManager;
    private BCRTicketInfo mBCRTicketInfo[] = {null, null};

    private String mServiceResult = null;
    private String mScanResult;
    private List<OC_YZJH_Detail> mYZJHList;

    private ProgressDialog progressDialog;
    private MyHandler handler;

    private Toolbar mToolbar;
//    private Switch mSwitch;
//    private TextView mBRXMText;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    private String ZYH;
    private String mStartDate;
    private String mEndDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_check);
        onBindUI();

        handler = new MyHandler(this);
        BCRListener mListener = new MyListener();
        mBCRManager = BCRManager.getInstance();
        mBCRManager.registerListener(mListener);

        mSwipeRefreshLayout.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        mSwipeRefreshLayout.setOnRefreshListener(this);

//        mSwitch.setOnCheckedChangeListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        InPatient inPatient = getMyApplication().getInPatient();
        if (inPatient != null) {
            ZYH = inPatient.getZYH();
            if (ZYH != null) {
                setToolbar(inPatient.getBRXM());
                Date date = new Date();
//                String dateString = myApplication.getSdf().format(date);
                String dateString = DateUtil.getDateTimeFormat(date);
                mStartDate = dateString;
                mEndDate = dateString;
//                doFlushData(false);
            }
        }
    }

    private void onBindUI() {
        mToolbar = findViewById(R.id.oc_toolbar);
//        mBRXMText = (TextView) findViewById(R.id.oc_tb_brxm);
//        mSwitch = (Switch) findViewById(R.id.oc_tb_switch);
        mSwipeRefreshLayout = findViewById(R.id.oc_swipe);
    }

    private void setToolbar(String brxm) {
        mToolbar.setTitle("医嘱计划复核");   //设置标题
        mToolbar.setTitleTextColor(Color.WHITE);
//        mBRXMText.setText(brxm);
//        mBRXMText.setTextColor(Color.WHITE);
//        mToolbar.setSubtitle(brxm);    //设置副标题
//        mToolbar.setSubtitleTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);   //必须使用
        //添加左边图标点击事件
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_order_check, menu); //解析menu布局文件到menu
        return true;
    }

    @Override
    public void onRefresh() {

    }

    /**
     * 获取医嘱计划操作
     */
    private class MyGetYZJHTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            isEcecuting[2] = true;
        }

        @Override
        protected String doInBackground(String... parms) {
            WebService getYZJHWebService = new WebService(OrdersCheckActivity.this);
            getYZJHWebService.setMETHOD_NAME("getYZJHResult");
            String result;
            getYZJHWebService.setPARMS(parms);
            result = getYZJHWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取医嘱计划列表为空！";
            } else {
                if (!result.equals(mServiceResult)) {
                    mServiceResult = result;
                    Gson gson = new Gson();
                    mYZJHList = gson.fromJson(mServiceResult, new TypeToken<List<OrderDetail>>() {
                    }.getType());
                    if (mYZJHList != null && mYZJHList.size() > 0) {
                        return null;
                    } else {
                        return "获取医嘱计划列表失败!";
                    }
                } else {
                    return "医嘱计划数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            isEcecuting[2] = false;
            if (s != null) {
                cancelProgressBar();
                if (!s.equals("医嘱计划数据未发生变化!")) {
                    Toast.makeText(OrdersCheckActivity.this, s, Toast.LENGTH_SHORT).show();
                } else {
//                    doFindDetail(2);
                }
            } else {
//                doSetKFD(mKFDList);
            }
        }
    }

    //显示等待对话框
    private void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消显示等待对话框
    private void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    //扫码监听
    private class MyListener implements BCRListener {
        @Override
        public void onScanFinished(int scanType, String elapseTime) {
            Log.d(TAG, "onScanFinished");
            mBCRTicketInfo = mBCRManager.getTicketInfo();
            Message msg = new Message();
            if (mBCRTicketInfo != null) {
                msg.what = 0x11;
            } else {
                msg.what = 0x99;
            }
            handler.sendMessage(msg);
        }

        @Override
        public void onOpened(boolean isReady) {
            Log.d(TAG, "onOpened");
            if (isReady) {
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_DATA_MATRIX);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_INTERLEAVED_2_OF_5);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_PDF417);
                mBCRManager.startScan(BCRManager.SCAN_TYPE_SINGLE, BCRManager.SCAN_MODE_CONTINUE);
            }
        }
    }

    private static class MyHandler extends Handler {

        WeakReference<OrdersCheckActivity> mActivity;

        MyHandler(OrdersCheckActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            OrdersCheckActivity activity = mActivity.get();
            activity.cancelProgressBar();
            switch (msg.what) {
                case 0x99:
                    Toast.makeText(activity, "获取扫描结果失败！", Toast.LENGTH_SHORT).show();
                    activity.mBCRManager.stopScan();
                    break;
                case 0x11: //获取扫描结果成功
                    activity.mBCRManager.stopScan();
                    String result = activity.mBCRTicketInfo[0].getTicketValue();
                    if (result != null && !result.equals("") && !result.equals("failed")) {
                        activity.mScanResult = result;
                    } else {
                        break;
                    }
                    String type = activity.mScanResult.substring(0, 2);
                    switch (type) {
                        case "SY":
//                            if (activity.mViewPager.getCurrentItem() != 0) {
//                                activity.mViewPager.setCurrentItem(0);
//                            } else {
//                                activity.doFindDetail(0);
//                            }
                            break;
                        case "ZS":
//                            if (activity.mViewPager.getCurrentItem() != 1) {
//                                activity.mViewPager.setCurrentItem(1);
//                            } else {
//                                activity.doFindDetail(1);
//                            }
                            break;
                        case "KF":
//                            if (activity.mViewPager.getCurrentItem() != 2) {
//                                activity.mViewPager.setCurrentItem(2);
//                            } else {
//                                activity.doFindDetail(2);
//                            }
                            break;
                        default:
                            break;
                    }
                    break;
            }
        }
    }

    private void doFlushData(boolean isSwipe) {
        if (!isSwipe) {
            showProgressBar(this);
        }
        String[] parms = {ZYH, mStartDate, mEndDate};
        new MyGetYZJHTask().execute(parms);
    }

}
